package com.ck.server.controller.test;

import com.ck.autoconfig.template.SmsTemplate;
import com.ck.common.constant.AjaxResult;
import com.ck.common.constant.CacheConstants;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;

/**
 * @author ck
 * @date 2023/4/17 14:11
 */

@RestController
@Slf4j
@Api(tags ="短信验证码接口")
public class SmsCodeController {

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private SmsTemplate smsTemplate;

    /**
     * 发送短信验证码接口
     *
     * @param phone
     * @return
     */
    @GetMapping("sendCode")
    public AjaxResult sendCheckCode(@RequestParam("phone") String phone) {
        String redisKey = CacheConstants.SMS_CODE_KEY + phone;
        //先判断该手机号发送的验证码是否还未失效
        if (this.redisTemplate.hasKey(redisKey)) {
            log.info("验证码还未失效");
        }
        //发送短信验证码
        String code = "123456";     /**测试用*/
//        String code = smsTemplate.sendCode(phone);
        if (StringUtils.isEmpty(code)) {
           log.info("发送验证码失败");
        }
        //短信发送成功，将验证码保存到redis中，有效期为5分钟
        redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));

        return new AjaxResult(200,"验证码发送成功");
    }
}
